/*
 * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package util;

import ninja.Context;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Singleton;

import java.io.IOException;
import java.io.StringWriter;

import ninja.bodyparser.BodyParserEngine;
import org.apache.commons.io.IOUtils;

@Singleton
public class BodyParserEngineTextPlain implements BodyParserEngine {

    private final Logger logger = LoggerFactory.getLogger(BodyParserEngineTextPlain.class);

    @Override
    public <T> T invoke(Context context, Class<T> classOfT) {
        String result = null;

        if (!classOfT.equals(String.class)) {
            logger.error("Can parse text/plain only into String. Requested is a {}", classOfT);
            throw new RuntimeException("Can parse text/plain only into String.");
        }

        try {
            StringWriter writer = new StringWriter();
            IOUtils.copy(context.getInputStream(), writer, "UTF-8");
            result = writer.toString();
        } catch (IOException ioException) {
            logger.error("Error parsing incoming text/plain", ioException);
        }

        return (T) result;
    }

    @Override
    public String getContentType() {
        return "text/plain";
    }
}
